package minh.bac.wcbrazil2014.netsupport;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;



import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class NetSupport {
	protected static String TAG = NetSupport.class.getSimpleName();
	private String contentType;
	private String userAgent;
	private int connectTimeout;
	private int soTimeout;
	private String authorization;
	private int numberRetry = 3;
	private boolean isInited = false;
	//private volatile static BaseNetSupportBeta instance;
	private  static NetSupport instance;
	/** Returns singleton class instance */
//	public static BaseNetSupportBeta getInstance() {
//		if (instance == null) {
//			synchronized (ImageLoader.class) {
//				if (instance == null) {
//					instance = new BaseNetSupportBeta();
//				}
//			}
//		}
//		return instance;
//	}
	
	
	public static NetSupport getInstance() {
	if (instance == null) {
		
			if (instance == null) {
				instance = new NetSupport();
			}
		
	}
	return instance;
}
	

	private NetSupport() {

	}

	public void init(NetConfig netConfig) {
		connectTimeout = netConfig.getConnectTimeout();
		soTimeout = netConfig.getSoTimeout();
		authorization = netConfig.getAuthorization();
		contentType = netConfig.getContentType();
		userAgent = netConfig.getUserAgent();
		numberRetry=netConfig.getNumberRetry();
	}

	private HttpClient myHttpClient() {
		HttpParams params = new BasicHttpParams();
		params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
				HttpVersion.HTTP_1_1);
		HttpConnectionParams.setConnectionTimeout(params, connectTimeout);
		HttpConnectionParams.setSoTimeout(params, soTimeout);
		HttpClient client = new DefaultHttpClient(params);
		return client;
	}

	public String method_GET(String url) {
		if(numberRetry==0) return null;
		int retryCount = 0;
		
		do {
			try {
				
				URL myUrl = new URL(url.replace(" ", "%20"));

				Log.d(TAG, "- method_GET -URl:" + myUrl);

				HttpURLConnection conn = (HttpURLConnection) myUrl
						.openConnection();
				conn.setConnectTimeout(connectTimeout);
				conn.setReadTimeout(soTimeout);
				if (authorization != null)
					conn.setRequestProperty("Authorization", authorization);

				conn.setRequestProperty("Content-Type", contentType);
				conn.setRequestProperty("User-Agent", userAgent);

				String jsonContent = readFromInputStream(conn
						.getInputStream());
				Log.d(TAG, "- method_GET - json result=" + jsonContent);

				conn.disconnect();
				return jsonContent;
			} catch (FileNotFoundException ex) {
				Log.d(TAG, "658345234 NetworkSupport - getNetworkData - FileNotFoundException = "
						+ ex.getMessage());

			} catch (Exception ex) {
				Log.d(TAG, "789345564 NetworkSupport - getNetworkData - Exception = "
						+ ex.getMessage());
			}
		} while (++retryCount < numberRetry);

		return null;
	}


	public String method_POST(String url, String bodySend) {
		if(numberRetry==0) return null;
		int retryCount = 0;

		do {
			try {

				URL myUrl = new URL(url);
				HttpClient client = myHttpClient();

				HttpConnectionParams.setConnectionTimeout(client.getParams(),
						connectTimeout);
				HttpResponse response;

				InputStream in = null;
				try {
					HttpPost post = new HttpPost(myUrl.toURI());

					StringEntity se = new StringEntity(bodySend, "UTF8");
					Log.d(TAG, "-method_POST - url=" + myUrl);
					Log.d(TAG, "-method_POST - json sent=" + bodySend);

					se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
							contentType));

					se.setContentEncoding(HTTP.UTF_8);

					post.setEntity(se);
					response = client.execute(post);

					/* Checking response */
					if (response != null) {
						in = response.getEntity().getContent(); // Get the data
					}

				} catch (Exception e) {
					Log.d(TAG, "576237 method_POST " + e.toString());
					return null;
				}
				String jsonContent = readFromInputStream(in);
				Log.d(TAG,"method_POST - response: " + jsonContent);
				return jsonContent;
			} catch (FileNotFoundException ex) {
				Log.d(TAG,"method_POST - getNetworkData - FileNotFoundException = "
						+ ex.getMessage());
				return null;

			} catch (Exception ex) {
				Log.d(TAG,"method_POST - getNetworkData - Exception = "
						+ ex.getMessage());
				return null;
			}
		} while (++retryCount < numberRetry);

	}

	/*
	 * protected static NetData parseResponseToNetData(String response, String[]
	 * keys) { NetData netData = new NetData(); if (response == null ||
	 * response.length() == 0) { netData.code = false; netData.msg =
	 * HomeActivity.str_connect_error;
	 * 
	 * return netData; } return BaseNetSupport.ParseJson(response, keys);
	 * 
	 * }
	 */
	public static String readFromInputStream(InputStream in) throws IOException {
		if (in == null)
			return null;
		StringBuilder sb = new StringBuilder();
		BufferedReader r = new BufferedReader(new InputStreamReader(in,"UTF-8"), 1000);
		for (String line = r.readLine(); line != null; line = r.readLine()) {
			sb.append(line);
		}
		in.close();
		String re=sb.toString();
		re.trim();
		if(re.charAt(0)==65279) sb.deleteCharAt(0);
		return sb.toString();
	}

	public static boolean isNetworkAvailable(Context context) {

		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null)
				for (int i = 0; i < info.length; i++)
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}

		}
		return false;
	}
	

}
